package com.newthread.android.dialog.dialoginformation;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import com.newthread.android.R;
import com.newthread.android.dialog.BaseDiaLog;

import java.io.File;
import java.io.IOException;


public class PalyMusicDiaLog extends BaseDiaLog<PalyMusicDiaLogConfig> {
    private Context context;
    private Vibrator vibrator;

    @Override
    public void initContentView() {
        context = PalyMusicDiaLog.this;
        setContentView(R.layout.dialog_paly_music);
    }

    @Override
    public void onInit(Bundle savedInstanceState) {
        final PalyMusicDiaLogConfig config = getDiaLogConfig();
        vibrate();
        palyMusic(config.getInformation());
    }

    private void palyMusic(String courseName) {
        final MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(context, Uri.parse("android.resource://" + context.getPackageName() + File.separator + R.raw.coursemusic));
            mp.setLooping(true);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (mp != null) {
                    mp.release();
                }
            }
        });
        alertDialog(courseName, mp);
    }

    private void alertDialog(String courseName, final MediaPlayer mp) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("停止播放音乐？");
        builder.setTitle(courseName);
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mp.release();
                vibrator.cancel();
                vibrator=null;
                dialog.dismiss();
                finish();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

    /**
     * 手机震动
     */
    private void vibrate() {
        try {
            vibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE);
            long[] pattern = {0,2000,2000,2000}; // OFF/ON/OFF/ON
            vibrator.vibrate(pattern, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
